const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const check = require('../../utils/check.js');
const rules = {
    name: '姓名',
    mobile: '手机',
    mail: "邮箱",
    workUnit: "工作单位",
    postName: "姓名",
    postNumber: '手机号',
    postAddress: '地址'
}
Page({
    data: {
        name: '',
        mobile: "",
        workUnit: "",
        isMember: "0",
        activityTitle: "",
        mail: '',
        activityId: '',
        phoneError: '',
        phoneError2: '',
        postAddress: "",
        postName: '',
        postNumber: '',
        postcode: '',
        isInform: "0",
        //提示
        postAddressError: "",
        postNameError: "",
        nameError: '',
        workUnitError: '',
        mailError: '',
        mobileError: '',
        postNumberError: "",
        meetingDocumentsUrl: '',
    },

    onChangeMeeting(e) {
        this.setData({
            isInform: e.detail,
            postAddress: "",
            postName: '',
            postNumber: '',
        })
    },
    //电话校验格式
    phoneCheck(e) {
        let results = check.isValidPhone(e.detail)
        this.setData({
            postNumberError: results
        })
    },
    phoneCheck2(e) {
        let results = check.isValidPhone(e.detail)
        this.setData({
            mobileError: results
        })
    },
    mailCheck(e) {
        let results = check.isValidMail(e.detail)
        this.setData({
            mailError: results
        })
    },
    onLoad(options) {
        const that = this
        that.setData({
            activityTitle: options.title,
            activityId: options.id
        });
        that.activityDetail()
        //初始化用户值
        that.getUser()
    },
    onShow() {
        const that = this;
        that.activityDetail()
        //初始化用户值
        that.getUser()
    },
   activityDetail(){
     const that=this
util.request(api.ActivityDetail, {id: that.data.activityId}, 'get').then(function (res) {
        if (res.errno === 200) {
            that.setData({
                meetingDocumentsUrl: res.data.meetingDocumentsUrl
            })
        }
    });
   },
    onShareAppMessage() {
        return {};
    },
    onChange(e) {
        this.setData({
            isMember: e.detail
        })
    },
    onSubmit() {
        //邮寄信息 ,postAddress,postName,postNumber
        const {
            isInform,
            name,
            mobile,
            workUnit,
            isMember,
            mail,
            activityId,
            activityTitle,
            postAddress,
            postName,
            postNumber,
            postcode
        } = this.data;
        let infoCreate = {
            isInform,
            name,
            mobile,
            workUnit,
            isMember,
            mail,
            activityId,
            activityTitle,
            postAddress,
            postName,
            postNumber,
            postcode
        }
        let infoApply = {}
        if (isInform == '1') {
            infoApply = {
                name,
                mobile,
                workUnit,
                postAddress,
                postName,
                postNumber,
            }
        } else {
            infoApply = {
                name,
                mobile,
                workUnit,
            }
        }
        let hasError = false
        let keys = Object.keys(infoApply);
        for (let i = 0; i < keys.length; i++) {
            let message = this.validate(null, keys[i])
            if (message) {
                hasError = true;
            }
        }
        if (hasError) {
            wx.showToast({
                title: '字段填写不完整',
                icon: 'error',
                duration: 2000
            })
            return;
        }
        this.requestApi(infoCreate)
    },
    validate(e, objKey) {
        let {key} = (e && e.target.dataset) || {}
        let curKey = objKey || key;
        if (!rules.hasOwnProperty(curKey)) return ''
        let curVal = this.data[curKey];
        let message = '';
        if (!curVal) {
            this.setData({
                [curKey + 'Error']: rules[curKey] + '不可为空',
            })
            message = rules[curKey] + '不可为空';
        } else {
            this.setData({
                [curKey + 'Error']: '',
            })
            message = ''
        }
        switch (objKey) {
            //postNumber
            case 'postNumber':
                message = check.isValidPhone(curVal)
                this.setData({
                    postNumberError: message
                })
                break;
            //    mail
            case 'mail':
                message = check.isValidMail(curVal)
                this.setData({
                    mailError: message
                })
                break;
            case 'mobile':
                message = check.isValidPhone(curVal)
                this.setData({
                    mobileError: message
                })
                break;
        }
        return message;
    },
    requestApi(infoApply) {
        const that = this
        util.request(api.ActivityApplyCreate, infoApply, 'post')
            .then(res => {
                if (res.errno === 200) {
                    const tmplIds = 'GdL9GGaogUjnzNDz2s9NiKkq7PgXjHcS2y2kNp0qLPM';
                    wx.requestSubscribeMessage({
                        tmplIds: [tmplIds],
                        success(res) {
                            if (res[tmplIds] == 'accept') {
                                //判断等于'accept'表示用户点击同意该条id对应的模板消息
                            } else {
                                wx.showToast({
                                    title: '您未同意接收会议文件通知',
                                    icon: 'none',
                                    duration: 2000
                                });
                            }
                        },
                        fail(err) {
                            console.error('订阅模板消息失败', err);
                            wx.showToast({
                                title: '订阅通知失败，请重试',
                                icon: 'none',
                                duration: 2000
                            });
                        }
                    })
                    //有会议通知文件的时候弹出提醒框
                    if (!that.data.meetingDocumentsUrl == "") {
                        wx.showModal({
                            title: '',
                            confirmColor: '#b4282d',
                            content: '恭喜您，报名成功！是否下载会议通知',
                            showCancel: true,
                            success: function (res) {
                                if (res.confirm) {
                                    // console.log(res)
                                    that.downloadAndOpenPDF();
                                    wx.navigateBack({
                                        delta: 1
                                    })
                                } else if (res.cancel) {
                                    wx.navigateBack({
                                        delta: 1
                                    })
                                    return console.log(res)
                                }

                            },
                            fail: function (res) {
                                console.log(res)
                                return console.log(res)
                            }
                        })
                    }else{
                        //没有时直接返回上一层
                        wx.navigateBack({
                            delta: 1
                        })
                        wx.showToast({
                            title: '报名成功!',
                            icon: 'success',
                            duration: 5000
                        })
                    }
                } else {
                    wx.showToast({
                        title: res.errmsg,//提示文字
                        duration: 2000,//显示时长
                        mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false
                        icon: 'error', //图标，支持"success"、"loading"
                    })
                }
            })
    },
    // 定义一个函数用于下载并打开PDF文件
    downloadAndOpenPDF() {
        const that = this; // 确保此处的that指向正确
        wx.downloadFile({
            url: that.data.meetingDocumentsUrl,
            success: function (res) {
              // console.log(that.data.meetingDocumentsUrl)
                const filePath = res.tempFilePath;
                wx.openDocument({
                    filePath: filePath,
                    showMenu: true
                });
                // 下载完成后，可以选择是否执行其他操作，比如返回上一页
                wx.navigateBack({
                    delta: 1
                });
            },
            fail: function (err) {
                wx.showToast({
                    title: '文件下载失败，请重试',
                    icon: 'none',
                    duration: 2000
                });
                // 可能需要根据实际情况处理下载失败的情况
            }
        });
    },

    getUser(){
        util.request(api.userInfoDetail, {id: wx.getStorageSync('userInfo').id}, 'get').then(res => {
            if (res.errno === 200) {
                this.setData({
                    name: res.data.nickName,
                    mobile: res.data.mobile,
                })
            } else {
                console.log(res.errmsg)
            }
        })
    }


});
